import java.util.Arrays;

public class MyArrayList implements List{
    private int[] elem;
    private int usedSize;


    private static final int DEFAULT_SIZE = 10;

    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    @Override
    public void display() {
        if(elem == null) return;
        int len = usedSize;
        for (int i = 0; i < len; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
    private void grow() {
        this.elem = Arrays.copyOf(this.elem,2 * elem.length);
    }


    @Override
    public void add(int data) {
        if(isFull()) {
            grow();
        }
        int ret = usedSize;
        this.elem[ret] = data;
        usedSize++;
    }

    @Override
    public boolean isFull() {
        return usedSize == elem.length;
    }

    @Override
    public void add(int pos, int date) {
        int len = usedSize;
        if(isFull()) {
            grow();
        }
        for (int i = len; i > pos; --i) {
            elem[i] = elem[i - 1];
        }
        elem[pos] = date;
        usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        int len = usedSize;
        for (int i = 0; i < len; i++) {
            if(this.elem[i] == toFind) return true;
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        int len = elem.length;
        for (int i = 0; i < len; i++) {
            if(this.elem[i] == toFind) return i;
        }
        return -1;
    }

    public void chackPos(int pos) throws PosException{
        int len = usedSize;
        if(pos < 0 ||pos > len) {
            throw new PosException("pos 不合法!!!");
        }
    }

    @Override
    public int get(int pos) {
        try {
            chackPos(pos);
            return elem[pos];
        }catch (PosException e) {
            System.out.println("输入pos位置不合法!!!");
            e.printStackTrace();
        }
        throw new PosException("pos 不合法!!!");
    }

    @Override
    public void set(int pos, int value) {
        try {
            chackPos(pos);
            elem[pos] = value;
        }catch (PosException e) {
            System.out.println("输入pos位置不合法!!!");
            e.printStackTrace();
        }
    }

    @Override
    public void remove(int key) {
        if(usedSize == 0) return;
        int ret = indexOf(key);
        if(ret >= 0) {
            for (int i = ret; i < usedSize - 1; i++) {
                elem[i] = elem[i + 1]; //elem[usedSize - 2] = elem[usedSize - 1];
            }
        }
        usedSize--;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        elem = null;
    }
}
